import * as types from '../../action-type'
import {toLogin, validate} from "../../../api/user";
import Mock from 'mockjs';
import permission from "../../../router/permission";
import router from "../../../router";
import {SET_MENU_PERMISSION} from "../../action-type";

const filterRouter = (authList) => {
    // 扁平化过滤
    authList = authList.map(item => item.auth); // 拿到授权的路由

    function filter(permission) {
        return permission.filter(route => { // 遍历配置的路由
            if (authList.includes(route.meta.auth)) {
                if (route.children) { // 嵌套路由
                    route.children = filter(route.children);
                }
                return route;
            }
        });
    }

    return filter(permission);
}

const userActions = {
    async [types.SET_USER]({commit}, {userInfo, hasPermission}) {
        commit(types.SET_USER, userInfo);
        commit(types.SET_PERMISSION, hasPermission);
    },
    async [types.SET_LOGIN]({commit, dispatch}, payload) {
        // 登录
        Mock.mock('http://127.0.0.1:7001/user/login', 'post', () => {
            return {
                err: 0,
                data: {
                    authList: [
                        {auth: 'lesson', name: '课程管理', path: '/profile/lesson-manager'},
                        {auth: 'student', name: '学员管理', path: '/profile/student-manager'},
                    ],
                    token: 's',
                    username: 'nb'
                }
            }
        })
        const userInfo = await toLogin(payload);
        dispatch(types.SET_USER, {userInfo, hasPermission: true})
    },
    async [types.VALIDATE]({commit, dispatch}, payload) {
        // 鉴权 先从localStore获取token
        if (!localStorage.getItem('token')) return false;
        Mock.mock('http://127.0.0.1:7001/user/validate', 'get', () => {
            return {
                err: 0,
                data: {
                    authList: [
                        {auth: 'lesson', name: '课程管理', path: '/profile/lesson-manager'},
                        {auth: 'student', name: '学员管理', path: '/profile/student-manager'},
                    ],
                    token: 's',
                    username: 'nb'
                }
            }
        })
        try {
            const userInfo = await validate();
            dispatch(types.SET_USER, {userInfo, hasPermission: true});
            return true;
        } catch(e) { // 如果token不存在
            dispatch(types.SET_USER, {userInfo: {}, hasPermission: false})
            return false;
        }
    },
    async [types.ADD_ROUTE]({commit, dispatch, state}, payload) {
        // 添加路由
        let authList = state.authList;
        let routes = filterRouter(authList);
        let route = router.options.routes.find((item) => {
            return item.path === '/profile';
        });
        console.log(route);
        route.children = routes; // 动态添加子元素
        router.addRoutes([route]); // 添加路由

        commit(types.SET_MENU_PERMISSION,  true); // 目录权限获取完毕
    }
}

export default userActions;